package com.pattern.singleton;

/**
 * lazy loading 懒汉式
 * 到达了按需初始化的目的, 但是带来了线程不安全的问题
 */
public class Mgr03 {

    private static Mgr03 INSTANCE;

    private Mgr03(){}

    /**
     * 此处有多个线程进入时 可能获取的instance都为空  就会产生多个对象
     * 故会出现线程安全问题
     * @return
     */
    public static Mgr03 getInstance(){
        if(INSTANCE == null){
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            INSTANCE = new Mgr03();
        }
        return INSTANCE;
    }

    public static void main(String[] args) {
        Long start = System.currentTimeMillis();
        for(int i = 0; i < 100; i++){
            new Thread(() -> {
                System.out.println(Mgr03.getInstance().hashCode());
            }).start();
        }
        Long end = System.currentTimeMillis();
        System.out.println("mill: " + (end - start));
    }
}
